function [ B ] = clusterstat( A, staFuncName, clusterLength, removeTrailIncompleteClu )
%CLUSTERSTAT 将二维矩阵沿列方向分为长度相等的多个簇，并调用统计函数对各簇沿列方向进行计算
%
% Input Arguments:
% A: 二维矩阵
% staFuncName: 字符串，统计函数名，可以为sum、cumsum、prod、cumprod、mean、mode、median、diff、std、var、max、min
% clusterLength: 标量，簇长度
% removeTrailIncompleteClu: 逻辑标量，true表示去掉末尾不足clusterLength的一簇，默认为true
%
% Output Arguments:
% B: 二维矩阵

% TODO: 调用splitapply
if nargin < 4
    removeTrailIncompleteClu = true;
end

if removeTrailIncompleteClu
    rowNum = floor(size(A, 1)/clusterLength);
else
    rowNum = ceil(size(A, 1)/clusterLength);
end
B = coder.nullcopy(NaN(rowNum, size(A, 2)));
if strcmp(staFuncName, 'sum') || strcmp(staFuncName, 'cumsum') || strcmp(staFuncName, 'prod') || strcmp(staFuncName, 'cumprod') ...
        || strcmp(staFuncName, 'mean') || strcmp(staFuncName, 'mode') || strcmp(staFuncName, 'median')
    for i=1:rowNum % 将循环体放入判断分支内以提高效率
        [bgnRowIdx, endRowIdx] = bgnendrowidx(i, clusterLength);
        B(i, :) = feval(staFuncName, A(bgnRowIdx:min(endRowIdx, end), :), 1);
    end
elseif strcmp(staFuncName, 'diff')
    for i=1:rowNum
        [bgnRowIdx, endRowIdx] = bgnendrowidx(i, clusterLength);
        B(i, :) = feval(staFuncName, A(bgnRowIdx:min(endRowIdx, end), :), 1, 1);
    end
elseif strcmp(staFuncName, 'std') || strcmp(staFuncName, 'var')
    for i=1:rowNum
        [bgnRowIdx, endRowIdx] = bgnendrowidx(i, clusterLength);
        B(i, :) = feval(staFuncName, A(bgnRowIdx:min(endRowIdx, end), :), 0, 1);
    end
elseif strcmp(staFuncName, 'max') || strcmp(staFuncName, 'min')
    for i=1:rowNum
        [bgnRowIdx, endRowIdx] = bgnendrowidx(i, clusterLength);
        B(i, :) = feval(staFuncName, A(bgnRowIdx:min(endRowIdx, end), :), [], 1);
    end
else
    error('Unsupported function name.');
end
end

function [bgnRowIdx, endRowIdx] = bgnendrowidx(i, clusterLength)
bgnRowIdx = (i-1)*clusterLength + 1;
endRowIdx = i * clusterLength;
end